package cn.intertion.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
import java.util.UUID;

/**
 * 验证码工具类
 * 文件名：CaptchaUtil.java
 */
public class CaptchaUtil {
    private static Integer width = 130;
    private static Integer height = 48;
    private static Integer num = 4;
    private static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z" };
    private static final Random ran = new Random();//随机数

    /**
     * 生成buffere Image图片
     *
     * @param finshCode 生成好的验证码字符串
     * @return
     */
    public static BufferedImage getCreateImg(String finshCode) {
        // 创建BufferedImage对象
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphic = img.createGraphics();// 创建画笔
        graphic.setColor(Color.WHITE);// 设置颜色
        graphic.fillRect(0, 0, width, height);//是用预定的颜色填充一个矩形，得到一个着色的矩形块。
        graphic.setColor(new Color(213, 213, 213));//设置边框颜色
        graphic.drawRect(0, 0, width - 1, height - 1);// 画正方形
        // 设置字体 风格 风格 高度
        Font font = new Font("宋体", Font.BOLD + Font.ITALIC, (int) (height * 0.8));
        graphic.setFont(font);
        for (int i = 0; i < num; i++) {
            // 随机设置字体RGB颜色
            graphic.setColor(new Color(ran.nextInt(200), ran.nextInt(200), ran.nextInt(200)));
            // 画出验证码
            graphic.drawString(String.valueOf(finshCode.charAt(i)), i * (width / num) + 4, (int) (height * 0.8));
        }
        for (int i = 0; i < (width + height); i++) {
            // 随机设置字体RGB颜色
            graphic.setColor(new Color(ran.nextInt(255), ran.nextInt(255), ran.nextInt(255)));
            // 生成干扰点
            graphic.drawOval(ran.nextInt(width), ran.nextInt(height), 1, 1);
        }
        for (int i = 0; i < 3; i++) {
            // 随机设置字体RGB颜色
            graphic.setColor(new Color(ran.nextInt(255), ran.nextInt(255), ran.nextInt(255)));
            // 随机生成干扰线
            graphic.drawLine(0, ran.nextInt(height), width, ran.nextInt(height));
        }

        return img;
    }
    public static String randomUUID5() {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < num; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        return shortBuffer.toString();
    }

//    public static void main(String[] args) throws IOException {
//
//        ImageIO.write(getCreateImg(randomUUID5()), "jpg", new File("F:\\abc.jpg"));
//    }
}


